<template>
  <div class="ann_list">
    <a-card>
      <div class="ann_title">
        <span>公告列表</span>
        <a-button type="primary" class="set_up" @click="onAddNew" icon="plus" v-action:add="'announcement'">发布公告</a-button>
      </div>
      <a-table
        :columns="columns"
        :data-source="ann_list"
        :pagination="paginationConfig"
        rowKey="id"
        :scroll="{x: true}"
        :loading="loading.table"
        style="margin-top:24px; margin-bottom:5px;"
        @change="onChangeTableConfig"
      >
        <span slot="action" slot-scope="row">
          <a @click="showAnnouncementContent(row.title ,row.content)">查看</a>
          <a-divider type="vertical" style="opacity: 1;" v-action:delete="'announcement'"/>
          <a @click="onDelete(row.id)" v-action:delete="'announcement'">删除</a>

        </span>
      </a-table>
    </a-card>
    <a-modal
      v-model="visible"
      title="创建新公告"
      @ok="onSubmit"
      :maskClosable="false"
      @cancel="onClose"
      cancelText="取消"
      okText="保存"
      :confirmLoading="loading.publish"
    >
      <a-form-model
        ref="annForm"
        :model="ann_form"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-model-item label="公告标题" prop="title">
          <a-input v-model="ann_form.title" placeholder="请输入公告标题" />
        </a-form-model-item>
        <a-form-model-item label="公告内容" prop="content">
          <a-textarea
            v-model="ann_form.content"
            placeholder="请输入公告内容"
            :auto-size="{ minRows: 3, maxRows: 10 }"
          />
        </a-form-model-item>
      </a-form-model>

    </a-modal>
  </div>
</template>

<script>

import {mapActions, mapMutations, mapState} from "vuex";

const columns = [
  {
    title: '公告标题',
    dataIndex: 'title',
  },
  {
    title: '公告内容',
    dataIndex: 'summary',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
  },
  {
    title: '操作',
    fixed: 'right',
    scopedSlots: { customRender: 'action' },
  }
]

const rules = {
  title: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入公告标题'
    },
    {
      max: 50,
      trigger: 'blur',
      message: '最大限制长度为100个字符'
    }
  ],
  content: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入公告内容'
    },
  ],
}

export default {
  name: "announcementList",
  data () {
    return {
      columns,
      rules,
      visible: false,
      loading: {
        table: false,
        publish: false
      },
      ann_list: [],
      ann_form: {
        title: "",
        content: ""
      }
    }
  },
  computed: {
    ...mapState('announcementManage',['paginationConfig'])
  },
  watch: {
    visible () {
      this.ann_form = {
        title: "",
        content: ""
      }
      this.$refs.annForm && (this.$refs.annForm.clearValidate())
    }
  },
  methods: {
    ...mapMutations('announcementManage',['setPage','setPageSize','setTotal','setOrder','setOrderBy']),
    ...mapActions('announcementManage', ['getAnnouncements','addAnnouncement','deleteAnnouncement']),
    getAnnouncementData () {
      this.loading.table = true
      this.getAnnouncements().then(res => {
        let data = res
        let summary = ""
        data.map(item => {
          if (typeof item.content === 'string' && item.content.length > 30){
            summary = item.content.substring(0,30) + "……"
          }else {
            summary = item.content
          }
          item.summary = summary
        })
        this.ann_list = data
      }).catch(e =>{
        console.error(e)
        this.$message.error('获取公告列表失败，原因：' + e.msg + '!')
      }).finally(() =>{
        this.loading.table = false
      })
    },
    onChangeTableConfig(pagination){
      this.setTotal(pagination.total)
      this.setPage(pagination.current)
      this.setPageSize(pagination.pageSize)
      this.getAnnouncementData()
    },
    showAnnouncementContent (title,content) {
      const h = this.$createElement;
      this.$info({
        title: title,
        content: h('div', {class:"text-wrapper"}, [
          h('p', content),
        ]),
        onOk() {},
      });
    },
    onAddNew () {
      this.visible = true
    },
    onDelete (id) {
      this.$confirm({
        title: '删除提示',
        content: '公告删除后无法恢复，您确定要继续吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          this.deleteAnnouncement(id).then(()=>{
            this.$message.success('公告删除成功')
            this.getAnnouncementData()
          }).catch((err) =>
            this.$message.error('公告删除失败，原因：' + err.msg + '！')
          )
        },
        onCancel: () => {},
      })
    },
    onSubmit () {
      this.$refs.annForm.validate(valid => {
        if (valid) {
          this.loading.publish = true
          this.addAnnouncement(this.ann_form).then(res => {
            this.visible = false
            this.$message.success('公告发布成功')
            this.getAnnouncementData()
          }).catch(err => this.$message.error('公告发布失败，原因：' + err.msg + '！'))
            .finally(() => {
              this.loading.publish = false
            })
        } else {
          setTimeout(()=>{
            this.loading.publish = false
            return false
          }, 1000)
        }
      })
    },
    onClose (){
      this.visible = false
      this.loading.publish = false
    }
  },
  mounted () {
    this.getAnnouncementData()
  },
}
</script>

<style scoped>
.ann_list{
  width: 100%;
  height: 100%;
}

.set_up{
  float: right;
}

.ant-drawer>>>.ant-drawer-body{
  height: calc(100% - 55px);
}

.ant-form{
  height: 100%;
  display: flex;
  flex-direction: column;
}

.submit_style{
  margin-bottom: 0;
  flex: 1;
}

.submit_style>>>.ant-col.ant-col-18.ant-form-item-control-wrapper{
  width: 100%;
  height: 100%;
}

.submit_style>>>.ant-form-item-control{
  display: flex;
  height: 100%;
  align-items: flex-end;
}

.submit_style>>>span.ant-form-item-children{
  width: 100%;
}

.ann_title{
  display: flex;
  justify-content: space-between;
}


.ann_title span {
  display: block;
  float: left;
  margin-bottom: 0;
  padding-right: 12px;
  color: rgba(0,0,0,.85);
  font-weight: 500;
  font-size: 16px;
  line-height: 32px;
}

.ant-table-wrapper>>>td.ant-table-row-cell-break-word {
  padding: 10px;
}

.text-wrapper {
  white-space: pre-wrap;
}

</style>

<style>
.ant-modal-body {
  padding: 24px 24px 24px 16px !important;
}

.ant-modal {
  top: 25px;
}

</style>
